import cn.edu.dgut.infomation.LocalUserInfo;
import cn.edu.dgut.utils.ReadFile;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/RegisterServlet")
/*@MultipartConfig*/
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String head_img = null;
       /* //接收头像
        Part part = request.getPart("headfile");
        //判断是否上传图片
        if(part.getSize()!=0){
            head_img = part.getSubmittedFileName();
            part.write(head_img);
        }else{
            head_img = "boy.png"; //如果没有上传图片，则设置为默认头像boy.png
        }*/
        Map<String, String> formMap = new HashMap<String, String>();    //保存文本域数据进 formMap 中
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> list = null;
        try {
            list = upload.parseRequest(request);
            for (FileItem fi : list ) {
                //判断是否是文本域
                if(fi.isFormField()){
                    String fieldName = fi.getFieldName();
                    formMap.put(fieldName,fi.getString("utf-8"));       //保存文本域数据进 formMap 中
                }else {
                    if(fi.getSize()!=0){ //判断文件上传框是否选择了图片
                        head_img = fi.getName();
                        String path = getServletContext().getRealPath("/uploadImages");
                        InputStream is = fi.getInputStream();
                        FileOutputStream os = new FileOutputStream(new File(path, head_img));
                        IOUtils.copy(is,os);
                        os.close();
                        is.close();
                        fi.delete();
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        if(head_img==null){    //head_img==null时，用户没有上传头像，则设置为默认头像 boy.png
            head_img="boy.png";
        }

        String user_number = new ReadFile().getMaxNumber();//生成工号
        LocalUserInfo localUserInfo = new LocalUserInfo(user_number,formMap.get("name"),formMap.get("phone_number"),formMap.get("email"),formMap.get("password"),head_img,null,null,null,null,null);
        Jsonb jsonb = JsonbBuilder.create();
        String userJson =jsonb.toJson(localUserInfo);
        new ReadFile().setUserInfo(userJson);  //保存信息进userInfo文件

        //保存登录信息，设置session并重定向到用户信息页面info.jsp
        Map<String, String> info = new HashMap<String, String>();
        info.put("user_number", user_number);
        info.put("name", formMap.get("name"));
        info.put("faculty_title", "NULL");
        info.put("group", "NULL");
        HttpSession session = request.getSession(true);
        session.setAttribute("isLogin", info);
        response.sendRedirect("/info.jsp");
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
